var currentEle;
retflag = false;

(function($){

	$.fn.QGLCustomValidatorNum=function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul><span></span></div></div>'
    
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=numberfieldvalidtion($(this).val());
	
	if(!flag){$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}    
	$(this).live("blur",function(){
		
	retflag=numberfieldvalidtion($(this).val());
		if (!retflag){$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});
	

	return retflag;
	}; 

    $.fn.quiggleDynamicJobAdd = function (templateBlock, placeHolder, indexBlock){
        $(this).click(function(){
//            alert("add address click " + templateBlock);
            var template = $(templateBlock);
            var indexField = $(indexBlock);
            var index = parseInt(indexField.text());
//            alert("index " + index);
            var templateClone = template.clone();
//            alert(templateClone.html());
            templateClone.html(templateClone.html().replace(/{index}/g, index));
            templateClone.attr('id', template.attr('id') + '-' + index)
//            templateClone.removeClass('template');
            templateClone.insertAfter($(placeHolder));
//            alert(templateClone.html());
            indexField.text(index + 1);
            templateClone.bindJobEvents();
            var statusField = templateClone.find("[name='job.statusId']");
//            alert(statusField.attr("name"));
            statusField.focus();
        });
    };

    $.fn.quiggleJobAutoComplete = function(dataSource, idField, dialogForm,nobrace){

        $( this ).autocomplete({
            minLength: 0,
//                source: projects,
            source: dataSource,
            focus: function( event, ui ) {
//                    $( "#project" ).val( ui.item.label );
                $(this).val( ui.item.initial);
                return false;
            },
            select: function( event, ui ) {
//                    $( "#project" ).val( ui.item.label );
                $(this).val( ui.item.initial);
//                    $( "#project-id" ).val( ui.item.value );
//                alert("change " + ui.item.id);
                $( this ).parent().find(idField).val( ui.item.id );
//                    $( "#project-description" ).html( ui.item.desc );
//                    $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );

                return false;
            },
            change: function(event, ui){
            	var textval=$.trim($(this).val()).toLowerCase();
    			var flag=true;
    			for (var i = 0; i < dataSource.length; i++) {
    				if ($.trim(dataSource[i].initial).toLowerCase() == textval) {
    					flag=false;
    					$( this ).parent().find(idField).val(dataSource[i].id);
    				}
    			}
                if(ui.item === null && flag){
//                       alert('ui is null');
                    $(this).parent().find(idField).val('');
                    $(dialogForm).find(".block-id").val($(this).parent().attr("id"));
                    $(dialogForm).find(".initial").val($(this).val());
                    $( dialogForm ).dialog("open");
                    currentEle=idField;
                }
                return false;
            }
        })
            .data( "autocomplete" )._renderItem = function( ul, item ) {
        	if(nobrace == 1){
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.initial  + "</a>" )
                .appendTo( ul );}
        	else{
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.initial + " (" +item.firstName + item.lastName + ")" + "</a>" )
                    .appendTo( ul );}
        };

    };

    $.fn.bindJobEvents = function(){

        $(this).find('.edit-job').each(function(){

            $(this).click(function(){
            	if($(this).attr("title")==2){
                $(this).closest(".job-record-block").find('.view').hide();
                $(this).closest(".job-record-block").find('.edit').show();
                $(this).closest(".job-record-block").find("[name='job.statusId']").focus();
				$(this).closest(".job-record-block").find(':input[value=""].edit:first').focus();
            	}
            	else {
            		$(this).parent().parent().find('.view').hide();
                    $(this).parent().parent().find('.edit').show();
                    $(this).parent().parent().find("[name='job.statusId']").focus();
            		
            	}
            })
        });

        $(this).find('.cancel-edit').each(function(){
            $(this).click(function(){
            	if($(this).attr("title")==2){
                     $(this).closest(".job-record-block").find('.edit').hide();
                    $(this).closest(".job-record-block").find('.view').show();
            	}
            	else
            	{
            		$(this).parent().parent().find('.edit').hide();
                    $(this).parent().parent().find('.view').show();
            	}
            })
        });


        $(this).find(".date-picker").each(function(){
            $(this).removeClass('hasDatepicker');
            $(this).datepicker();
        });

        $(this).find(".agency-initial").each(function(){
            $(this).quiggleJobAutoComplete(agencies, '.agency-id', "#agency-form");
        });

        $(this).find(".scopist-initial").each(function(){
            $(this).quiggleJobAutoComplete(scopists, '.scopist-id', "#scopist-form");
        });

        $(this).find(".proofer-initial").each(function(){
            $(this).quiggleJobAutoComplete(proofers, '.proofer-id',"#proofer-form");
        });



    };

})(jQuery);


$(document).ready(function(){

//navigating without saving
var warnMessage = "You have unsaved changes on this page!";

    $('input:not(:button,:submit)').change(function () {
        window.onbeforeunload = function () {
		 if (warnMessage != null) return warnMessage;
        }
    });
	
    $('input:submit').click(function(e) {
        warnMessage = null;
    });


//end of navigating without saving

    $(this).bindJobEvents();

   //$("#add-job").quiggleDynamicJobAdd("#job-template", "#job-placeholder", "#job-index");
   $(".numberVal").QGLCustomValidatorNum("number",false); 

$(".job-record-block").live("submit",function(){
	if(retflag)	{
	
$(".numberVal").QGLCustomValidatorNum("number",true,this);}

 flag=retflag;
	return flag;
	
});
$(".ui-dialog-buttonset").live("click",function(){
	
	$(currentEle).closest("div").next().find("input:visible").focus();

});
/** HIGHLIGHT  COLUMNS **/

$(".job-column").bind("focusin",function(){
var colindex=$(this).index();
var rowindex=$(this).closest(".job-row").index();
$(this).addClass("higlightclass");
var parentwin=$(".job-table:eq(0)").find(".job-row:eq("+rowindex+")").find(".job-column:eq("+colindex+")").addClass("higlightclass");
});

$(".job-column").bind("focusout",function(){
var colindex=$(this).index();
var rowindex=$(this).closest(".job-row").index();
 $(this).removeClass("higlightclass");
var parentwin=$(".job-table:eq(0)").find(".job-row:eq("+rowindex+")").find(".job-column:eq("+colindex+")").removeClass("higlightclass");
});
/** HIGHLIGHT END ***/	



});







$(function() {
    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
//		$( "#dialog:ui-dialog" ).dialog( "destroy" );

    var name = $( "#name" ),
        email = $( "#email" ),
        password = $( "#password" ),
        allFields = $( [] ).add( name ).add( email ).add( password ),
        tips = $( ".validateTips" );

    var agencyInitial = $("#agency-initial"),
        agencyName = $("#agency-name"),
        allAgencyFields = $([]).add(agencyInitial).add(agencyName),
        agencyTips = $(".agency-validation-tips");


    function updateTips( t ) {
        tips
            .text( t )
            .addClass( "ui-state-highlight" );
        setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
    }

    function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTips( "Length of " + n + " must be between " +
                min + " and " + max + "." );
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
        } else {
            return true;
        }
    }

    $( "#agency-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create an agency": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );
				var str ='';
				var eFlag = false;
//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    /*
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     */
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    agency.find('.agency-id').val('0');
                    agency.find('.agency-initial').val($("#agency-initial").val())
                    agency.find('.agency-name').val($("#agency-name").val())
                    agency.find('.agency-initial').focus();

					if($.trim($("#agency-initial").val()) == "")
					{
						str +='Initial is Required.';
						eFlag = true;
					}
					if($.trim($("#agency-name").val()) == "")
					{
						str +='Name is Required.';
						eFlag = true;
					}
					$("#detail-agency-form-errorMSGDiv").html(str);
					if(eFlag)
						return;
					
                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
//            alert($(this).attr("id"));
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
        }
    });
    
    $( "#agency-form1" ).dialog({
        autoOpen: false,
        height: 250,
        width: 950,
        modal: true,
        buttons: {
            "Create a proofer new rate item": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );

//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    /*
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     */
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    
                    agency.find('.proofer-rate-item-id').val('0');                    
                    agency.find('.proofer-rate-item-code').val($('#proofer-rate-item-code').val());
                    agency.find('.proofer-rate-item-code-description').val($('#proofer-rate-item-code-description').val());
                    agency.find('.proofer-rate-item-value').val($('#proofer-rate-item-value').val());
                    agency.find('.proofer-rate-item-unit').val($('#proofer-rate-item-unit').val());
                    agency.find('.proofer-rate-item-perunit').val($('#proofer-rate-item-perunit').val());
                    agency.find('.proofer-rate-item-reimbursable').val($('#proofer-rate-item-reimbursable').val());
                    agency.find('.proofer-rate-item-taxable').val($('#proofer-rate-item-taxable').val());                    
                    agency.find('.proofer-rate-item-code').focus();
                    
                    
                    var rateItemDetails={                    		
                    		
    						code:$('#proofer-rate-item-code').val(),
    						codeDescription:$('#proofer-rate-item-code-description').val(),
    						value:$('#proofer-rate-item-value').val(),
    						unit:$('#proofer-rate-item-unit').val(),
    						perUnit:$('#proofer-rate-item-perunit').val(),
    						reimbursable:$('#proofer-rate-item-reimbursable').is(":checked"),
    						taxable:$('#proofer-rate-item-taxable').is(":checked") ,
    						type:"",
    						ccval:0,
    						entityUserId:$('.proofer-id').val()
    						
                        };
                    
                    callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetails,agency.find('.proofer-rate-item-id').attr("id"));

                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
//            alert($(this).attr("id"));
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
        }
    });

   $( "#scopist-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create a scopist": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );
					
				var eFlag = false;
				var str = '';
				
//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    agency.find('.scopist-id').val('0');
                    agency.find('.scopist-initial').val($("#scopist-initial").val())
                    agency.find('.scopist-name').val($("#scopist-name").val())
                    agency.find('.scopist-initial').focus();

					if($.trim($("#scopist-initial").val()) == "")
					{
						str +='Initial is Required.';
						eFlag = true;
					}
					if($.trim($("#scopist-name").val()) == "")
					{
						str +='Name is Required.';
						eFlag = true;
					}
					$("#detail-scopist-form-errorMSGDiv").html(str);
					if(eFlag)
						return;
					
                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
//            alert($(this).attr("id"));
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
        }
    });
   
   
   $( "#agency-rate-item-form" ).dialog({
       autoOpen: false,
       height: 250,
       width: 950,
       modal: true,
       buttons: {
           "Create a new agency rate item": function() {
               var bValid = true;
               allAgencyFields.removeClass( "ui-state-error" );

//               bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
               // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

               if ( bValid ) {
                   
                    $( "#users tbody" ).append( "<tr>" +
                    "<td>" + name.val() + "</td>" +
                    "<td>" + email.val() + "</td>" +
                    "<td>" + password.val() + "</td>" +
                    "</tr>" );
                    
                   var block = $(this).find('.block-id').val();
                   var agency = $('#' + block);

                 /*  agency.find('.scopist-id').val('0');
                   agency.find('.scopist-initial').val($("#scopist-initial").val())
                   agency.find('.scopist-name').val($("#scopist-name").val())
                   agency.find('.scopist-initial').focus();
                   
                   */
                   
                   
                   
                   agency.find('.agency-rate-item-id').val('0');                    
                   agency.find('.agency-rate-item-code').val($('#agency-rate-item-code').val());
                   agency.find('.agency-rate-item-code-description').val($('#agency-rate-item-code-description').val());
                   agency.find('.agency-rate-item-value').val($('#agency-rate-item-value').val());
                   agency.find('.agency-rate-item-unit').val($('#agency-rate-item-unit').val());
                   agency.find('.agency-rate-item-perunit').val($('#agency-rate-item-perunit').val());
                   agency.find('.agency-rate-item-reimbursable').val($('#agency-rate-item-reimbursable').val());
                   agency.find('.agency-rate-item-taxable').val($('#agency-rate-item-taxable').val());                    
                   agency.find('.agency-rate-item-code').focus();
                   
                   
                 
                   
                   var rateItemDetails={                    		
                   		
   						code:$('#agency-rate-item-code').val(),
   						codeDescription:$('#agency-rate-item-code-description').val(),
   						value:$('#agency-rate-item-value').val(),
   						unit:$('#agency-rate-item-unit').val(),
   						perUnit:$('#agency-rate-item-perunit').val(),
   						reimbursable:$('#agency-rate-item-reimbursable').is(":checked"),
   						taxable:$('#agency-rate-item-taxable').is(":checked") ,
   						type:"",
   						ccval:0,
   						entityUserId:$('.agency-id').val()
   						
                       };
                   
                   callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetails, agency.find('.agency-rate-item-id').attr("id"));

                   $( this ).dialog( "close" );
               }
           },
           Cancel: function() {
               $( this ).dialog( "close" );
           }
       },
       close: function() {
//           alert($(this).attr("id"));
           allAgencyFields.val( "" ).removeClass( "ui-state-error" );
       }
   });
   
   
   
   
   $( "#scopist-rate-item-form" ).dialog({
       autoOpen: false,
       height: 250,
       width: 950,
       modal: true,
       buttons: {
           "Create  scopist new rate item": function() {
               var bValid = true;
               allAgencyFields.removeClass( "ui-state-error" );

//               bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
               // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

               if ( bValid ) {
                   /*
                    $( "#users tbody" ).append( "<tr>" +
                    "<td>" + name.val() + "</td>" +
                    "<td>" + email.val() + "</td>" +
                    "<td>" + password.val() + "</td>" +
                    "</tr>" );
                    */
                   var block = $(this).find('.block-id').val();
                   var agency = $('#' + block);
                   
                 
                
                 /*  agency.find('.scopist-id').val('0');
                   agency.find('.scopist-initial').val($("#scopist-initial").val())
                   agency.find('.scopist-name').val($("#scopist-name").val())
                   agency.find('.scopist-initial').focus();*/                    
                 
                   agency.find('.scopist-rate-item-id').val('0');                    
                   agency.find('.scopist-rate-item-code').val($('#scopist-rate-item-code').val());
                   agency.find('.scopist-rate-item-code-description').val($('#scopist-rate-item-code-description').val());
                   agency.find('.scopist-rate-item-value').val($('#scopist-rate-item-value').val());
                   agency.find('.scopist-rate-item-unit').val($('#scopist-rate-item-unit').val());
                   agency.find('.scopist-rate-item-perunit').val($('#scopist-rate-item-perunit').val());
                   agency.find('.scopist-rate-item-reimbursable').val($('#scopist-rate-item-reimbursable').val());
                   agency.find('.scopist-rate-item-taxable').val($('#scopist-rate-item-taxable').val());                    
                   agency.find('.scopist-rate-item-code').focus();
                   
                   var rateItemDetails={                    		
                   		
						code:$('#scopist-rate-item-code').val(),
						codeDescription:$('#scopist-rate-item-code-description').val(),
						value:$('#scopist-rate-item-value').val(),
						unit:$('#scopist-rate-item-unit').val(),
						perUnit:$('#scopist-rate-item-perunit').val(),
						reimbursable:$('#scopist-rate-item-reimbursable').is(":checked"),
						taxable:$('#scopist-rate-item-taxable').is(":checked") ,
						entityUserId:$('.scopist-id').val(),
						type:"",
						ccval:0,
						jobId:$('.jobId').val()
						
                   };
                   
                   callAjaxToSaveTheNewScopistRateItemDetails(rateItemDetails,agency.find('.scopist-rate-item-id').attr("id"));
                   
                   $( this ).dialog( "close" );
               }
           },
           Cancel: function() {
               $( this ).dialog( "close" );
           }
       },
       close: function() {
//           alert($(this).attr("id"));
           allAgencyFields.val( "" ).removeClass( "ui-state-error" );
       }
   });
    
 

    $( "#proofer-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create a proofer": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );
				var str ='';
				var eFlag = false;

//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    /*
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     */
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    agency.find('.proofer-id').val('0');
                    agency.find('.proofer-initial').val($("#proofer-initial").val())
                    agency.find('.proofer-name').val($("#proofer-name").val())
                    agency.find('.proofer-initial').focus();

					if($.trim($("#proofer-initial").val()) == "")
					{
						str +='Initial is Required.';
						eFlag = true;
					}
					if($.trim($("#proofer-name").val()) == "")
					{
						str +='Name is Required.';
						eFlag = true;
					}
					$("#detail-proofer-form-errorMSGDiv").html(str);
					if(eFlag)
						return;

                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
//            alert($(this).attr("id"));
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
        }
    });

});
$(document).ready(function(){
	
$(".callAjaxTGetAgencyCodes").click(function(){
		
		var entityid=$(this).closest(".job-table").find(".agency-id").val();
		var valueReq = $(this).closest(".job-table").find(".type-id");
		//callAjaxTGetAgencyCodes(entityid,$(this),valueReq,"#agency-form");
		
		callAjaxToGetAgencyCodes(entityid,$(this),valueReq,"");
		
		
	});
	
  $(".job-id").change(function(){
	
	var agencyId=$('.agency-id').val();
	var jobId = $.trim($('.job-id').val());
	
	if(jobId == "")
		$(".job-id").val("");
	
	if( agencyId != "" && jobId !="" )
	callAjaxToCheckJobIdExistance(agencyId,jobId);
  });
  
  /*$(".note").focus(function(){ 
  	
  	
  	$('#notes').text($(this).val());
	
  	$('#notes-form').dialog({
  		width:374,
  		
  		buttons: {
  	           "Ok": function() {
  	        	   $('.note').val($('#notes').val());
  	        	   $( this ).dialog( "close" );
  	             
  	           },
  	           Cancel: function() {
  	               $( this ).dialog( "close" );
  	           }
  	     }
  	});
  	
  });
  
  $('.witnes').focus(function(){
  	
  	$('#witness').text($(this).val());    	
  	
  	$('#witness-form').dialog({
  		width:374,    		
  		buttons: {
  	           "Ok": function() {
  	        	   $('.witnes').val($('#witness').val());
  	        	   $( this ).dialog( "close" );    	             
  	            },
  	           Cancel: function() {
  	               $( this ).dialog( "close" );
  	           }
  	    }
  	});
  }); */
	

});
function callAjaxToCheckJobIdExistance(agencyId,jobId){
	
	var rateItemDetails ={     
			"agencyId":agencyId,
			"jobId":jobId		
			
	};
	
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?checkJobIdExistance',//name of action?name of method in action
		  dataType: 'json',
		  //data: {agencyId:agencyId,jobId:jobId},
		  data:{rateItemDetails:JSON.stringify(rateItemDetails)},
			 
		  success: function(result){
			  
			 if(result!=0){				 
				 alert("Job ID already exist.");
				 $('.job-id').val('');
				 }
		    
		 },
		  error:function() { 
			  
		  }
	});
	
}

function callAjaxToGetAgencyCodes(entityid,idField,valueReq,formId)
{

	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?getCodes',//name of action?name of method in action
		  dataType: 'json',
		  data: {entityUserId:entityid},
			 
		  success: function(result){

			  var codes = new Array();

			                  for(var i in result)
			                  {
			                	  var obj = {
			                			};

			                	  obj["value"] = result[i].codeName;
			                	  obj["id"] = result[i].rateItemId;
			                	  obj["initial"] =result[i].codeName;
			                	  obj["lastName"] = "";
			                	  obj["firstName"] = "";
			                	  codes.push(obj);
			                	  
			                  }

			            
			           //  console.log(codes);  
		            $(idField).quiggleJobAutoComplete(codes, valueReq, formId,1);
		    
		 },
		  error:function() { 
		
		  }
	}); 

}

function numberfieldvalidtion(eleVal){
		var flag=true;
		if(isNaN(eleVal))
			flag = false;
		else if(eleVal % 1 != 0)
			flag = false;
		return flag;	
		}

